<template>
	<view class="wanlfind-add-container">
		<view class="edgeInsetTop"></view>
		<view class="wanlfind-add-container__main">
			<view class="want">

				<view class="want card-style">
					<view class="padding-bj flex justify-between align-center">
						<view class="text-30 text-bold">Өгөгдөл байршуулах</view>
					</view>
					<!-- 新增描述 -->
					<view class="text-sm text-grey padding-lr-bj margin-top-xs">
						Эзэмшигчийн үнэмлэхний мэдээлэл <!-- 需在语言包补充此字段 -->
					</view>
					<view class="grid col-4 grid-square flex-sub padding-lr-bj">
						<view v-if="params.images.length > 0" v-for="(item, index) in params.images" :key="index">
							<view class="item shadow-sm" @tap="handlePreview(index)">
								<image :src="$wanlshop.oss(item, 100, 100)" mode="aspectFill"></image>
							</view>
							<view class="tag bg-red" @tap="handleDelImage(index)">
								<text class="wlIcon-31guanbi text-white"></text>
							</view>
						</view>
						<view v-if="params.images.length < 9" @tap="handleImage()">
							<view class="item bg-grey-light flex align-center justify-center border-dashed">
								<view class="text-center">
									<text class="wlIcon-tianjia text-xxl text-grey"></text>
									<view v-if="params.images.length === 0" class="margin-top-xs text-sm">
										Зураг нэмнэ үү</view>
									<view v-else class="margin-top-xs text-sm">Үргэлжлүүлэн нэмээрэй</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				
				 <!-- 汽车图片上传区域（添加描述提示） -->
				  <view class="want card-style">
					<view class="padding-bj flex justify-between align-center">
					  <view class="text-30 text-bold">Машины зураг</view>
					</view>
					<!-- 新增描述 -->
					<view class="text-sm text-grey padding-lr-bj margin-top-xs">
					 Машины ерөнхий дүр төрхийг харуулсан зургийг оруулаарай <!-- 需补充语言字段 -->
					</view>
					<view class="grid col-4 grid-square flex-sub padding-lr-bj">
					  <view v-if="params.avatar">
						<view class="item shadow-sm" @tap="handlePreviewAvatar">
						  <image :src="$wanlshop.oss(params.avatar, 100, 100)" mode="aspectFill"></image>
						</view>
						<view class="tag bg-red" @tap="handleDelAvatar">
						  <text class="wlIcon-31guanbi text-white"></text>
						</view>
					  </view>
					  <view v-if="!params.avatar" @tap="handleAvatar">
						<view class="item bg-grey-light flex align-center justify-center border-dashed">
						  <view class="text-center">
							<text class="wlIcon-tianjia text-xxl text-grey"></text>
							<view class="margin-top-xs text-sm">Зураг нэмнэ үү</view>
						  </view>
						</view>
					  </view>
					</view>
				  </view>

				<view class="padding-bj card-style">
					<!-- 入驻类型选择 -->
					<view class="padding-bj">
						<view class="text-30">Загвар</view>
						<radio-group @change="handleSettleTypeChange">
							<label class="flex align-center margin-top-sm">
								<radio value="ачааны машин" :checked="settleType === 'ачааны машин'" />
								<text class="margin-left-sm">ачааны машин</text>
							</label>
							<label class="flex align-center margin-top-sm">
								<radio value="автобус"
									:checked="settleType === 'автобус'" />
								<text class="margin-left-sm">автобус</text>
							</label>
						</radio-group>
					</view>
				</view>
				<!-- 用户名输入框 -->
				<view v-if="userInfo.needUsername" class="padding-bj">
					<view class="text-30">Эзэмшигчийн нэр</view>
					<input v-model="params.username"
						placeholder="Эзэмшигчийн нэр"
						class="input bg-gray padding-lr-bj radius-bock margin-top-sm" />
				</view>
				<!-- 手机号输入框 -->
				<view v-if="userInfo.needPhone" class="padding-bj">
					<view class="text-30">Холбоо барих мэдээлэл</view>
					<input v-model="params.phone"
						placeholder="Холбоо барих мэдээлэл"
						class="input bg-gray padding-lr-bj radius-bock margin-top-sm" />
				</view>

				<!-- 手机号输入框 -->
				<view v-if="userInfo.needEmail" class="padding-bj">
					<view class="text-30">Мэйл</view>
					<input v-model="params.email"
						:placeholder="Мэйл"
						class="input bg-gray padding-lr-bj radius-bock margin-top-sm" />
				</view>

				<!-- 内容 -->

				<view class="padding-bj flex justify-between align-center" v-if="userInfo.needContent">
					<view class="text-30">
						<text class="wlIcon-xiugaioryijian margin-right-xs text-bold"></text>
						Танилцуулга
					</view>
				</view>
				<view class="padding-bj bg-gray margin-lr-bj radius-bock" v-if="userInfo.needContent">
					<editor id="editor" v-model="params.content" @ready="onEditorReady" @input="onEditorInput"
						placeholder="Танилцуулга" />
				</view>
			</view>

			<checkbox-group :class="checked == 1 ? 'shake-horizontal' : ''" class="auth-clause"
				@change="CheckboxChange">
				<checkbox class="orange" :class="checked == 2 ? 'checked' : ''" :checked="checked == 2 ? true : false"
					value="2" />
				<view>
					Би уншсан<text
						@tap="onDetails(params.id, $t('pages.user.request.入驻协议'))">Төлбөрийн гэрээ</text>
				</view>
			</checkbox-group>
		</view>
		<!-- 底部 -->
		<view class="safeAreaBottom"></view>
		<view class="wanlfind-add-container__foot">
			<view class="cu-bar tabbar foot flex flex-direction">
				<button class="cu-btn bg-red lg" @tap="handleSubmit">
					<text class="wlIcon-fabu margin-right-sm"></text>

					Элсэх хүсэлт гаргах
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				modalName: null,
				orderList: [],
				current_page: 1, //当前页码
				last_page: 1, //总页码
				status: 'loading',
				chooseList: [],
				video: {
					tempFilePath: null, // 本地缓存
					progress: 0, //上传进度
					totalBytesSent: 0, //已经上传的数据长度
					totalBytesExpectedToSend: 0, //预期需要上传的数据总长度
				},
				params: {
					type: null,
					content: '',
					images: [],
					username: '',
					phone: '',
					card_number: '',
					bank_name: '',
					email: '',
					wx: '',
					avatar: ''
				},
				requiredData: [], // 存储 required_data 字段的值
				settleType: '', // 用户选择的入驻类型（'企业' 或 '个人'）
				fee_switch: 0,
				userInfo: {
					needUsername: true,
					needPhone: true,
					needBankName: false,
					needCardNumber: false,
					needBankName: false,
					needEmail: false,
					needContent: false,
					needSettleType: false // 是否需要选择入驻类型
				},
				checked: 0
			};
		},
		onLoad(option) {
			// this.params.type = option.type;
			this.params.id = option.id;
			this.getArrivalInfo();
		},
		methods: {
			CheckboxChange(e) {
				this.checked = e.detail.value;
			},
			handleSettleTypeChange(e) {
				this.settleType = e.detail.value;
				if (e.detail.value == 'ачааны машин') {
					this.params.type = 1;
				} else {
					this.params.type = 2;
				}
			},
			async getArrivalInfo() {
				try {
					await uni.request({
						url: '/wanlshop/Arrival/arrivalInfo',
						method: 'GET',
						data: {
							id: this.params.id
						},
						success: res => {
							// 更新 userInfo
							this.requiredData = res.data.required_data ? res.data.required_data.split(
								',') : [];
							// 根据 requiredData 更新 userInfo
							this.userInfo.needPhone = this.requiredData.includes('2');
							this.userInfo.needEmail = this.requiredData.includes('3');
							this.userInfo.needContent = this.requiredData.includes('4');
							this.fee_switch = res.data.fee_switch;
						}
					});
				} catch (error) {
					this.$wanlshop.msg('网络错误，请重试');
				}
			},

			// 发布
			async handleSubmit() {
				if (this.checked == 0) {
					this.$wanlshop.msg('Эхлээд нэвтрэх гэрээг шалгана уу');
					return;
				}
				const params = this.params;
				// 校验入驻类型
				if (this.userInfo.needSettleType && !this.settleType) {
					this.$wanlshop.msg('Та оруулахыг хүссэн загвараа сонгоно уу');
					return;
				}
				// 校验对公账户（企业类型）
				// if (this.settleType === this.$t('pages.user.request.企业') && !this.params.public_account) {
				// 	this.$wanlshop.msg(this.$t('pages.user.request.请输入对公账户'));
				// 	return;
				// }
				await uni.request({
					url: '/wanlshop/Arrival/addData',
					method: 'POST',
					data: params,
					success: res => {
						this.$wanlshop.msg('Хэрэглээний амжилт');
						this.$wanlshop.to('/pages/page/success?type=arrival');
					}
				});
			},

			handleImage() {
				uni.chooseImage({
					crop: {
						quality: 60
					},
					success: res => {
						uni.request({
							url: '/wanlshop/common/uploadData',
							success: updata => {
								for (let i = 0; i < res.tempFilePaths.length; i++) {
									// 读取图片宽高
									uni.getImageInfo({
										src: res.tempFilePaths[i],
										success: image => {
											uni.uploadFile({
												url: updata.data.uploadurl,
												filePath: image.path,
												name: 'file',
												formData: updata.data
													.storage == 'local' ?
													null : updata.data
													.multipart,
												success: data => {
													this.params.images
														.push(JSON.parse(
																data.data)
															.data.url);
												},
												fail: error => {
													uni.showToast({
														title: JSON
															.parse(
																error
																.data
																)
															.msg,
														icon: 'error',
														position: true
													});
												}
											});
										}
									});
								}
							}
						});
					}
				});
			},
			handlePreview(index) {
				let imgArr = [];
				for (let item of this.params.images) {
					imgArr = imgArr.concat(this.$wanlshop.oss(item, 500));
				}
				uni.previewImage({
					urls: imgArr,
					current: imgArr[index],
					indicator: 'number'
				});
			},
			handleDelImage(index) {
				this.params.images.splice(index, 1);
			},



			// 选择并上传头像
			handleAvatar() {
				uni.chooseImage({
					count: 1, // 限制为单张图片
					crop: {
						quality: 60
					},
					success: res => {
						const tempFilePath = res.tempFilePaths[0];
						uni.request({
							url: '/wanlshop/common/uploadData',
							success: updata => {
								uni.getImageInfo({
									src: tempFilePath,
									success: image => {
										uni.uploadFile({
											url: updata.data.uploadurl,
											filePath: image.path,
											name: 'file',
											formData: updata.data.storage ==
												'local' ? null : updata.data
												.multipart,
											success: data => {
												// 将上传结果单独赋值给avatar字段
												const response = JSON
													.parse(data.data);
												this.params.avatar =
													response.data.url;
											},
											fail: error => {
												uni.showToast({
													title: JSON
														.parse(
															error
															.data)
														.msg,
													icon: 'error'
												});
											}
										});
									}
								});
							}
						});
					}
				});
			},

			// 删除头像
			handleDelAvatar() {
				this.params.avatar = '';
			},

			// 预览头像
			handlePreviewAvatar() {
				if (this.params.avatar) {
					uni.previewImage({
						urls: [this.$wanlshop.oss(this.params.avatar, 500)],
						current: 0
					});
				}
			},
		
			onEditorInput(e) {
				this.params.content = e.detail.html;
			},
			onEditorReady() {
				// #ifdef MP-BAIDU
				this.editorCtx = requireDynamicLib('editorLib').createEditorContext('editorId');
				// #endif

				// #ifdef APP-PLUS || H5 ||MP-WEIXIN
				uni.createSelectorQuery()
					.select('#editor')
					.context(res => {
						this.editorCtx = res.context;
					})
					.exec();
				// #endif
			}
		}
	};
</script>

<style lang="scss">
	.input {
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
	}

	.card-style {
	  border-radius: 16rpx;
	  box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.03);
	  margin-bottom: 30rpx;
	  overflow: hidden;
	}
	
	.item {
	  border-radius: 12rpx;
	  overflow: hidden;
	  image {
	    display: block;
	    width: 100%;
	    height: 180rpx;
	    object-fit: cover;
	    transition: transform 0.2s;
	  }
	  &:active image {
	    transform: scale(0.98);
	  }
	}

	.wanlfind-add-container {
		&__main {
			.video {
				.upload {
					position: relative;
					width: 220rpx;
					height: 300rpx;

					video {
						width: 220rpx;
						height: 300rpx;
					}

					.loading {
						position: absolute;
						top: 0;
						bottom: 0;
						right: 0;
						left: 0;
					}
				}

				#editor {
					flex: 1;
					height: 240rpx;
					min-height: 100rpx;
				}
			}

			.grid {
				position: relative;

				.item {
					position: absolute;
					top: 0;
					bottom: 0;
					left: 0;
					right: 0;
					z-index: 1;
					display: flex;
					justify-content: center;
					align-items: center;
					text-align: center;
					border-radius: 18rpx;
					overflow: hidden;
					background-color: #f0f0f0;
				}

				.tag {
					position: absolute;
					top: 0rpx;
					right: 0rpx;
					z-index: 3;
					width: 40rpx;
					height: 40rpx;
					border-radius: 5500rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					text-align: center;
					overflow: hidden;
					background-color: #e6162c;
				}
			}
		}

		&__foot {
			.tabbar {
				z-index: 10;
				background-color: transparent;

				.cu-btn {
					width: calc(100% - 50rpx);
					font-size: 32rpx;
					height: 86rpx;
				}
			}
		}

		&__modal {
			.scroll-y {
				padding-bottom: 0;

				.item {
					display: flex;

					image {
						width: 120rpx;
						height: 120rpx;
						flex-shrink: 1;
					}

					.details {
						&>view {
							width: 100%;
						}

						flex: 1;
						display: flex;
						flex-wrap: wrap;
						align-content: space-between;
					}
				}
			}
		}
	}
</style>